const app = getApp()
const commissionApi = require('../../../utils/commissionApi.js');
Page({
  data: {
    balance: 0.00,       // 从后端获取
    amount: '',          // 输入金额
    alipayAccount: '',
    realName: ''
  },

  onLoad() {
    this.loadBalance();
  },

  loadBalance() {
    commissionApi.getBalance()
    .then(res =>{
      this.setData({
        balance:res.balance
      })
    })
  },

  onInputAmount(e) {
    this.setData({ amount: e.detail.value });
  },

  onInputAlipayAccount(e) {
    this.setData({ alipayAccount: e.detail.value });
  },

  onInputRealName(e) {
    this.setData({ realName: e.detail.value });
  },

  onSubmit() {
    const { amount, alipayAccount, realName, balance } = this.data;
  
    // 金额校验
    if (!amount || parseFloat(amount) <= 0) {
      return wx.showToast({ title: '请输入正确的金额', icon: 'none' });
    }
  
    if (parseFloat(amount) > balance) {
      return wx.showToast({ title: '超出可提现余额', icon: 'none' });
    }
  
    // 支付宝账号校验
    if (!alipayAccount || alipayAccount.length < 5) {
      return wx.showToast({ title: '请输入正确的支付宝账号', icon: 'none' });
    }
  
    // 实名人校验
    if (!realName || realName.length < 2) {
      return wx.showToast({ title: '请输入真实姓名', icon: 'none' });
    }
  
    wx.showLoading({ title: '提交中...' });
  
    // 发起提现申请
    commissionApi.applyWithdrawal({
      amount: amount,
      account: alipayAccount,
      realname: realName,
    }).then(res => {
      wx.hideLoading();
      wx.showToast({ title: '提现申请已提交', icon: 'success' });
  
      // 清空输入框并刷新余额
      this.setData({
        amount: '',
        alipayAccount: '',
        realName: ''
      });
      this.loadBalance();
      this.loadWithdrawList && this.loadWithdrawList(); // 如果页面有提现列表，则刷新
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ title: err.message || '提交失败，请稍后重试', icon: 'none' });
    });
  }
  
});
